package com.aabte.nettyleran.netty.file;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;

/**
 * 1、Netty文件服务器启动，绑定8080作为内部监听端口
 * 2、在CMD控制台，通过telnet和文件服务器建立TCP连接
 * 3、在控制台输入需要下载的文件绝对路径
 * 4、文件服务器接收到请求消息后进行合法性判断，如果文件存在，则将文件发送给CMD控制台
 * 5、CMD控制台打印文件和文件内容
 *
 * @author Daniel
 * @version 1.0
 * @date 2020/3/15
 */
public class FileServer {


    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        new FileServer().run(port);
    }

    private void run(int port) throws InterruptedException {
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boosGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        ch.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
                        ch.pipeline().addLast(new FileServerHandler());
                    }
                });

        try {
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            System.out.println("Start file server at port: " + port);
            channelFuture.channel().closeFuture().sync();
        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private static class FileServerHandler extends SimpleChannelInboundHandler<String> {

        public static final String CR = System.getProperty("line.separator");

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }

        @Override
        protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
            File file = new File(msg);
            if (file.exists()) {
                if (!file.isFile()) {
                    ctx.writeAndFlush("Not a file: " + file + CR);
                    return;
                }
                ctx.write(file + " " + file.length() + CR);
                RandomAccessFile randomAccessFile = new RandomAccessFile(msg, "r");
                FileRegion fileRegion = new DefaultFileRegion(randomAccessFile.getChannel(), 0, randomAccessFile.length());
                ctx.write(fileRegion);
                ctx.writeAndFlush(CR);
                randomAccessFile.close();
            } else {
                ctx.writeAndFlush("File not found: " + file + CR);
            }
        }
    }
}
